package cn.cntv.app.ipanda.custom;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;

/**
 * 自定义 Gson 方法式的 Volley 请求
 *
 * @param <T>
 */
public class GsonRequest<T> extends Request<T> {

    private final Listener<T> mListener;
    private Class<T> mClass;

    public GsonRequest(int method, String url, Class<T> clazz,
                       Listener<T> listener, ErrorListener errorListener) {
        super(method, url, errorListener);

        this.mClass = clazz;
        this.mListener = listener;
    }

    public GsonRequest(String url, Class<T> clazz, Listener<T> listener,
                       ErrorListener errorListener) {

        this(Method.GET, url, clazz, listener, errorListener);
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {

        try {

            String tJson = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));

            Gson tGson = new Gson();

            return Response.success(tGson.fromJson(tJson, mClass),
                    HttpHeaderParser.parseCacheHeaders(response));

        } catch (Exception e) {

            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(T response) {
        mListener.onResponse(response);
    }
}
